package fr.cephb.berkeley.baseapi.bindings;

import java.io.ByteArrayOutputStream;


import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

public abstract class AbstractTupleBinding<T>
	extends TupleBinding<T>
	{
	public void writeCString(String s,TupleOutput output)
		{
		if(s==null) throw new NullPointerException();
		try
			{
			output.write(s.getBytes());
			}
		catch(Exception err)
			{
			throw new RuntimeException(err);
			}
		output.writeByte(0);
		}
	public String readCString(TupleInput input)
		{
		ByteArrayOutputStream out= new ByteArrayOutputStream();
		int c;
		while((c=input.readUnsignedByte())!=0)
			{
			out.write((byte)c);
			}
		return new String(out.toByteArray());
		}
	
	public long readInt64(TupleInput input)
		{
		long a= readInt32(input);
		long b= readInt32(input);
		long	number = a | (b << 32);
		return number;
		}
	
	public void writeInt64(long i,TupleOutput output)
		{
		output.writeLong(i);
		}
	
	
	public int readInt32(TupleInput input)
		{
		try {
		byte array[]=new byte[4];
		//if(input.read(array)!=4) throw new IndexOutOfBoundsException("Expected to read 4 bytes");
		/* int number =  (int)(array[3] << 24)
			| (int)(array[2]  << 16)
			| (int)(array[1]  << 8)
			|  (int)(array[0] );*/
		int number =	input.readUnsignedByte() |
				input.readUnsignedByte()<<8 |
				input.readUnsignedByte()<<16 |
				input.readUnsignedByte()<<24
				;
		return number;
		} catch(Exception err)
			{
			throw new RuntimeException(err);
			}
		}
	public void writeInt32(int i,TupleOutput output)
		{
		output.writeInt(i);
		}
	
	public short readInt16(TupleInput input)
		{
		try {
		byte array[]=new byte[2];
                //if(input.read(array)!=2) throw new IndexOutOfBoundsException("expected reading 2 bytes");
                short number =  (short)(
			 input.readUnsignedByte() |
			(input.readUnsignedByte() << 8)
			);
                return number;
                } catch(Exception err)
                        {
                        throw new RuntimeException(err);
                        }
		}
	public void writeInt16(short s,TupleOutput output)
		{
		output.writeShort(s);
		}

	}
